package com.franklin.java.utils;

import com.google.gson.Gson;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Franklin
 * @since 2021/08/28 20:39
 */
public class JsonUtils {

    public static <K,V> Map<K,V> parseMap(String jsonStr){
        Gson gson = new Gson();
        return gson.fromJson(jsonStr, LinkedHashMap.class);
    }

    public static <K,V> Map<K,V> parseMap(String jsonStr,Class<K> keyType,Class<V> valueType){
        Map<Object, Object> map = parseMap(jsonStr);
        Map<K,V> result = new LinkedHashMap<>();
        map.forEach((k,v) -> {
            String valueJsonStr = toJsonString(v);
            V value = parseObject(valueJsonStr, valueType);
            result.put((K) k,value);
        });
        return result;
    }

    public static <E> String toJsonString(E entity){
        Gson gson = new Gson();
        return gson.toJson(entity);
    }

    public static <E> E parseObject(String jsonStr,Class<E> type){
        Gson gson = new Gson();
        return gson.fromJson(jsonStr,type);
    }
}
